<template>
  <div class="room-container">
    <div class="header">
      <h2>房间管理</h2>
      <el-button type="primary" @click="handleAdd">新增房间</el-button>
    </div>

    <!-- 搜索区域 -->
    <div class="search-area">
      <el-form :inline="true" :model="searchForm" class="search-form">
        <el-form-item label="所属家庭">
          <el-select 
            v-model="searchForm.family_id" 
            placeholder="请选择家庭"
            clearable
            @clear="handleSearch"
            class="search-select"
          >
            <el-option
              v-for="item in familyList"
              :key="item.family_id"
              :label="item.family_name"
              :value="item.family_id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="房间名称">
          <el-select 
            v-model="searchForm.room_name" 
            placeholder="请选择房间名称"
            clearable
            @clear="handleSearch"
            class="search-select"
          >
            <el-option
              v-for="item in roomNameList"
              :key="item"
              :label="item"
              :value="item"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="房间类型">
          <el-select 
            v-model="searchForm.room_type" 
            placeholder="请选择房间类型"
            clearable
            @clear="handleSearch"
            class="search-select"
          >
            <el-option label="卧室" value="卧室" />
            <el-option label="客厅" value="客厅" />
            <el-option label="厨房" value="厨房" />
            <el-option label="卫生间" value="卫生间" />
            <el-option label="书房" value="书房" />
          </el-select>
        </el-form-item>
        <el-form-item class="search-buttons">
          <el-button type="primary" @click="handleSearch">查询</el-button>
          <el-button @click="handleReset">重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 表格 -->
    <el-table :data="roomList" style="width: 100%" v-loading="loading" border stripe>
      <el-table-column type="index" label="序号" width="80" align="center" />
      <el-table-column prop="room_name" label="房间名称" />
      <el-table-column prop="room_type" label="房间类型" />
      <el-table-column label="所属家庭" width="180">
        <template #default="{ row }">
          {{ getFamilyName(row.family_id) }}
        </template>
      </el-table-column>
      <el-table-column prop="created_at" label="创建时间" width="180" />
      <el-table-column label="操作" width="200">
        <template #default="{ row }">
          <el-button type="primary" link @click="handleEdit(row)">编辑</el-button>
          <el-button type="danger" link @click="handleDelete(row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 新增/编辑对话框 -->
    <el-dialog
      :title="dialogType === 'add' ? '新增房间' : '编辑房间'"
      v-model="dialogVisible"
      width="500px"
    >
      <el-form
        ref="formRef"
        :model="formData"
        :rules="rules"
        label-width="100px"
      >
        <el-form-item label="房间名称" prop="room_name">
          <el-input v-model="formData.room_name" />
        </el-form-item>
        <el-form-item label="房间类型" prop="room_type">
          <el-select v-model="formData.room_type" placeholder="请选择房间类型">
            <el-option label="卧室" value="卧室" />
            <el-option label="客厅" value="客厅" />
            <el-option label="厨房" value="厨房" />
            <el-option label="卫生间" value="卫生间" />
            <el-option label="书房" value="书房" />
          </el-select>
        </el-form-item>
        <el-form-item label="所属家庭" prop="family_id">
          <el-select v-model="formData.family_id" placeholder="请选择所属家庭">
            <el-option
              v-for="item in familyList"
              :key="item.family_id"
              :label="item.family_name"
              :value="item.family_id"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmit">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  getRoomList,
  addRoom,
  updateRoom,
  deleteRoom,
  getRoomByFamilyId
} from '@/api/room'
import { getFamilyList } from '@/api/family'

// 数据列表
const roomList = ref([])
const familyList = ref([])
const loading = ref(false)

// 对话框相关
const dialogVisible = ref(false)
const dialogType = ref('add')
const formRef = ref(null)
const formData = ref({
  room_name: '',
  room_type: '',
  family_id: ''
})

// 表单校验规则
const rules = {
  room_name: [{ required: true, message: '请输入房间名称', trigger: 'blur' }],
  room_type: [{ required: true, message: '请选择房间类型', trigger: 'change' }],
  family_id: [{ required: true, message: '请选择所属家庭', trigger: 'change' }]
}

// 搜索表单
const searchForm = ref({
  family_id: '',
  room_name: '',
  room_type: ''
})

// 房间名称列表（用于下拉选择）
const roomNameList = computed(() => {
  return [...new Set(roomList.value.map(room => room.room_name))]
})

// 获取家庭名称的方法
const getFamilyName = (familyId) => {
  const family = familyList.value.find(f => f.family_id === familyId)
  return family ? family.family_name : '未知家庭'
}

// 获取房间列表
const getList = async () => {
  try {
    loading.value = true
    let res
    
    // 如果选择了家庭，使用 getRoomByFamilyId
    if (searchForm.value.family_id) {
      res = await getRoomByFamilyId(searchForm.value.family_id)
    } else {
      res = await getRoomList()
    }

    // 根据搜索条件过滤数据
    let filteredData = res.data
    
    if (searchForm.value.room_name) {
      filteredData = filteredData.filter(item => 
        item.room_name.toLowerCase().includes(searchForm.value.room_name.toLowerCase())
      )
    }
    
    if (searchForm.value.room_type) {
      filteredData = filteredData.filter(item => 
        item.room_type === searchForm.value.room_type
      )
    }
    
    roomList.value = filteredData
  } catch (error) {
    console.error('获取房间列表失败:', error)
  } finally {
    loading.value = false
  }
}

// 查询按钮点击
const handleSearch = () => {
  getList()
}

// 重置按钮点击
const handleReset = () => {
  searchForm.value = {
    family_id: '',
    room_name: '',
    room_type: ''
  }
  getList()
}

// 获取家庭列表
const getFamilies = async () => {
  try {
    const res = await getFamilyList()
    familyList.value = res.data
  } catch (error) {
    console.error('获取家庭列表失败:', error)
  }
}

// 新增按钮点击
const handleAdd = () => {
  dialogType.value = 'add'
  formData.value = {
    room_name: '',
    room_type: '',
    family_id: ''
  }
  dialogVisible.value = true
}

// 编辑按钮点击
const handleEdit = (row) => {
  dialogType.value = 'edit'
  formData.value = { ...row }
  dialogVisible.value = true
}

// 删除按钮点击
const handleDelete = (row) => {
  ElMessageBox.confirm('确认删除该房间吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      await deleteRoom(row.room_id)
      ElMessage.success('删除成功')
      getList()
    } catch (error) {
      console.error('删除失败:', error)
    }
  })
}

// 提交表单
const handleSubmit = async () => {
  if (!formRef.value) return
  
  await formRef.value.validate(async (valid) => {
    if (valid) {
      try {
        if (dialogType.value === 'add') {
          await addRoom(formData.value)
          ElMessage.success('添加成功')
        } else {
          await updateRoom(formData.value)
          ElMessage.success('修改成功')
        }
        dialogVisible.value = false
        getList()
      } catch (error) {
        console.error('操作失败:', error)
      }
    }
  })
}

// 初始化数据
const initData = async () => {
  try {
    // 获取家庭列表
    await getFamilies()
    
    // 获取房间列表
    await getList()
  } catch (error) {
    console.error('初始化数据失败:', error)
  }
}

// 组件挂载时获取数据
onMounted(() => {
  initData()
})
</script>

<style scoped>
.room-container {
  padding: 20px;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.search-area {
  background-color: #fff;
  padding: 20px;
  border-radius: 4px;
  margin-bottom: 20px;
}

.search-form {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
}

/* 调整表单项样式 */
:deep(.el-form-item) {
  margin-bottom: 15px;
  margin-right: 15px;
}

:deep(.el-form-item__label) {
  font-weight: 500;
  color: #606266;
}

/* 统一下拉选择框宽度和样式 */
:deep(.search-select) {
  width: 200px;
}

:deep(.search-select .el-input__inner) {
  height: 32px;
  line-height: 32px;
  background-color: #fff;
  border: 1px solid #dcdfe6;
  color: #606266;
}

/* 按钮组样式 */
.search-buttons {
  margin-left: auto;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

/* 确保下拉选项文字可见 */
:deep(.el-select-dropdown__item) {
  padding: 0 20px;
  color: #606266;
}

:deep(.el-select-dropdown__item.selected) {
  color: #409EFF;
  font-weight: 700;
}

/* 优化表单布局 */
:deep(.el-form--inline) {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
  align-items: flex-start;
}

/* 调整表单项间距 */
:deep(.el-form-item) {
  margin-right: 20px;
  margin-bottom: 10px;
}

/* 确保选择框内容完整显示 */
:deep(.el-select__tags) {
  max-width: calc(100% - 30px);
}
</style> 